import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/file_list_viewmodel.dart';
import 'package:provider/provider.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';

enum _Type { DELETE, CREATE, PRIVACY }

class FileListWidget extends StatelessWidget {
  final FileType type;
  final bool isMe;
  final String userId;
  final ValueNotifier<bool> _delete = ValueNotifier(false);
  final ValueNotifier<bool> _privacy = ValueNotifier(false);

  FileListWidget({Key key, this.type, this.userId, this.isMe = true}) : super(key: key);

  Widget _getMenu(BuildContext context) {
    return PopupMenuButton(
      itemBuilder: (BuildContext context) {
        return [
          PopupMenuItem<_Type>(
            value: _Type.DELETE,
            child: Container(
              height: 45.w,
              child: Row(
                children: <Widget>[
                  Image.asset(
                    'images/trash_can.png',
                    width: 40.w,
                    height: 41.w,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 17.w),
                    child: Text(
                      '删除',
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF696C72),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          PopupMenuItem<_Type>(
            value: _Type.CREATE,
            child: Container(
              height: 45.w,
              child: Row(
                children: <Widget>[
                  Image.asset(
                    'images/create_file.png',
                    width: 40.w,
                    height: 39.w,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 17.w),
                    child: Text(
                      '新建文件夹',
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF696C72),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ];
      },
      onSelected: (type) {
        if (type == _Type.DELETE) {
          _delete.value = true;
        } else if (type == _Type.PRIVACY) {
          _privacy.value = true;
        } else {
          bool show = true;
          if (this.type == FileType.KNOWLEDGE || this.type == FileType.APPLY) {
            show = false;
          }
          showDialog(
              context: context,
              child: DialogUtil.getCreateFileDialog(context, showPrivate: show,
                  onCreate: (select, text) {
                Provider.of<FileListViewModel>(context, listen: false)
                    .createFile(text, !select, onError: (msg) => Toast.show(msg, context));
              }));
        }
      },
      child: Text(
        "···",
        style: TextStyle(
            letterSpacing: 5.w,
            fontSize: 39.sp,
            fontWeight: FontWeight.bold,
            color: Color(
              0xFF696C72,
            )),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<FileListViewModel>(
      create: (_) {
        FileListViewModel model = FileListViewModel(type, userId);
        model.loadData();
        return model;
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: MySubassembly.getBackIcon(context, color: Colors.black),
                  ),
                  Expanded(
                    flex: 4,
                    child: Center(
                      child: Text(
                        getName(),
                        style: TextStyle(
                            fontSize: 32.sp, color: Theme.of(context).textTheme.subtitle2.color),
                      ),
                    ),
                  ),
                  Expanded(
                    child: MySubassembly.getSearchIcon(null,
                        text: isMe
                            ? Builder(builder: (context) => _getMenu(context))
                            : Constants.empty),
                  ),
                ],
              ),
            ),
          ),
        ),
        body: Selector<FileListViewModel, BaseState>(
            builder: (context, state, __) {
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              }
              if (state == BaseState.EMPTY) {
                return EmptyWidget(
                  content: '${getName()}为空',
                );
              }
              if (state == BaseState.FAIL) {
                return FailWidget(onClick: () {
                  Provider.of<FileListViewModel>(context, listen: false).loadData();
                });
              }
              if (state == BaseState.CONTENT) {
                ScrollController _scrollController = ScrollController();
                _scrollController.addListener(() {
                  if (_scrollController.position.pixels ==
                      _scrollController.position.maxScrollExtent) {
                    context.read<FileListViewModel>().nextData();
                  }
                });
                return Container(
                  decoration: BoxDecoration(
                    border: Border(top: BorderSide(width: 1.h, color: Color(0xFFEBECF1))),
                    color: Theme.of(context).backgroundColor,
                  ),
                  child: Column(
                    children: <Widget>[
                      ValueListenableProvider.value(
                        value: _delete,
                        builder: (context, _) {
                          bool delete = context.watch<bool>();
                          return delete
                              ? Container(
                                  padding: EdgeInsets.only(left: 35.w, top: 30.h),
                                  alignment: Alignment.centerLeft,
                                  width: double.infinity,
                                  child: _deleteWidget(context),
                                )
                              : Constants.empty;
                        },
                      ),
                      Expanded(child: Builder(builder: (context) {
                        var list = context.watch<FileListViewModel>().list;
                        return Container(
                          margin: EdgeInsets.only(top: 30.h, left: 35.w, right: 35.w),
                          child: GridView.count(
                            controller: _scrollController,
                            crossAxisCount: 3,
                            mainAxisSpacing: 20.w,
                            crossAxisSpacing: 20.w,
                            childAspectRatio: 0.75,
                            children: list.map((entity) => _itemWidget(entity)).toList(),
                          ),
                        );
                      })),
                      ValueListenableProvider.value(
                        value: _delete,
                        builder: (context, _) {
                          return context.watch<bool>()
                              ? Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () async {
                                          bool delete = await showDialog<bool>(
                                              context: context,
                                              builder: (context) {
                                                return AlertDialog(
                                                    title: Text(StringResources.ti_shi),
                                                    content: Text(
                                                      '是否确认删除已选文件夹？',
                                                      style: TextStyle(
                                                          color: Theme.of(context)
                                                              .textTheme
                                                              .subtitle2
                                                              .color),
                                                    ),
                                                    actions: <Widget>[
                                                      FlatButton(
                                                        child: Text(StringResources.qu_xiao),
                                                        onPressed: () =>
                                                            Navigator.of(context).pop(),
                                                      ),
                                                      FlatButton(
                                                        child: Text(StringResources.shan_chu),
                                                        onPressed: () {
                                                          Navigator.of(context).pop(true);
                                                        },
                                                      ),
                                                    ]);
                                              });
                                          if (delete != null && delete) {
                                            context.read<FileListViewModel>().deleteFiles();
                                          }
                                          _delete.value = false;
                                        },
                                        child: Container(
                                          width: double.infinity,
                                          height: 98.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xfff2f2f2),
//                                            border: Border.all(
//                                                color: Colors.black26,
//                                                width: 0.5),
                                          ),
                                          child: Center(
                                            child: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: <Widget>[
//                                                Image.asset(
//                                                  'images/trash_can.png',
//                                                  width: 32.w,
//                                                  height: 32.w,
//                                                ),
                                                Padding(
                                                  padding: EdgeInsets.only(left: 19.w),
                                                  child: Text(StringResources.shan_chu),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () {
                                          _delete.value = false;
                                        },
                                        child: Container(
                                          width: double.infinity,
                                          height: 98.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xff0cb7d9),
//                                            border: Border.all(
//                                                color: Colors.black26,
//                                                width: 0.5),
                                          ),
                                          child: Center(
                                            child: Text(
                                              StringResources.qu_xiao,
                                              style: TextStyle(color: Colors.white),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              : Constants.empty;
                        },
                      ),
                      ValueListenableProvider.value(
                        value: _privacy,
                        builder: (context, _) {
                          return context.watch<bool>()
                              ? Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () async {
                                          bool delete = await showDialog<bool>(
                                              context: context,
                                              builder: (context) {
                                                return AlertDialog(
                                                    title: Text(StringResources.ti_shi),
                                                    content: Text(
                                                      '是否确认修改已选文件夹的权限？',
                                                      style: TextStyle(
                                                          color: Theme.of(context)
                                                              .textTheme
                                                              .subtitle2
                                                              .color),
                                                    ),
                                                    actions: <Widget>[
                                                      FlatButton(
                                                        child: Text(StringResources.qu_xiao),
                                                        onPressed: () =>
                                                            Navigator.of(context).pop(),
                                                      ),
                                                      FlatButton(
                                                        child: Text(StringResources.que_ding),
                                                        onPressed: () {
                                                          Navigator.of(context).pop(true);
                                                        },
                                                      ),
                                                    ]);
                                              });
                                          if (delete) {
                                            context.read<FileListViewModel>().changePrivacyAll();
                                          }
                                          _privacy.value = false;
                                        },
                                        child: Container(
                                          width: double.infinity,
                                          height: 98.h,
                                          decoration: BoxDecoration(
                                            color: Theme.of(context).backgroundColor,
                                            border: Border.all(color: Colors.black26, width: 0.5),
                                          ),
                                          child: Center(
                                            child: Row(
                                              mainAxisSize: MainAxisSize.min,
                                              children: <Widget>[
                                                Image.asset(
                                                  'images/privacy.png',
                                                  width: 40.w,
                                                  height: 40.w,
                                                ),
                                                Padding(
                                                  padding: EdgeInsets.only(left: 19.w),
                                                  child: Text(StringResources.bao_cun),
                                                )
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () {
                                          _privacy.value = false;
                                        },
                                        child: Container(
                                          width: double.infinity,
                                          height: 98.h,
                                          decoration: BoxDecoration(
                                              color: Theme.of(context).backgroundColor,
                                              border:
                                                  Border.all(color: Colors.black26, width: 0.5)),
                                          child: Center(
                                            child: Text(StringResources.qu_xiao),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                              : Constants.empty;
                        },
                      ),
                    ],
                  ),
                );
              }
              return Text('');
            },
            selector: (_, model) => model.mState),
      ),
    );
  }

  String getName() {
    String name;
    if (type == FileType.INSPIRATION) {
      name = StringResources.ling_gan;
    } else if (type == FileType.MATERIAL) {
      name = StringResources.su_cai;
    } else if (type == FileType.IMAGE) {
      name = StringResources.cai_ji;
    } else if (type == FileType.KNOWLEDGE) {
      name = StringResources.zhi_shi;
    } else {
      name = StringResources.ying_yong;
    }
    return name;
  }

  Widget _deleteWidget(BuildContext context) {
    ValueNotifier<bool> _allDelete = ValueNotifier(false);
    return Material(
      color: Colors.transparent,
      child: GestureDetector(
        onTap: () {
          if (_allDelete.value) {
            context.read<FileListViewModel>().unSelectAll();
          } else {
            context.read<FileListViewModel>().selectAll();
          }
          _allDelete.value = !_allDelete.value;
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ValueListenableProvider<bool>.value(
              value: _allDelete,
              builder: (context, _) {
                return context.watch<bool>()
                    ? Image.asset(
                        'images/select@2x.png',
                        fit: BoxFit.cover,
                        width: 28.w,
                        height: 28.w,
                      )
                    : Container(
                        width: 28.w,
                        height: 28.w,
                        decoration:
                            BoxDecoration(border: Border.all(color: Colors.black26, width: 0.5)),
                      );
              },
            ),
            Padding(
              padding: EdgeInsets.only(left: 5.w),
              child: Text(
                '全选',
                style: TextStyle(fontSize: 28.sp, color: Colors.black26),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _itemWidget(FileLoxen entity) {
    return ValueListenableProvider.value(
      value: _delete,
      builder: (context, _) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onLongPress: () {
            if (entity.canEdit == 1 && isMe && !_delete.value && !_privacy.value) {
              changeName(context, entity);
            }
          },
          onTap: () {
            if (_delete.value) {
              context.read<FileListViewModel>().deleteChange(entity);
            } else if (_privacy.value) {
              context.read<FileListViewModel>().changePrivacy(entity);
            } else {
              if (type == FileType.KNOWLEDGE || type == FileType.APPLY) {
                Navigator.of(context).pushNamed(Routes.mineStudyFolder, arguments: [
                  type == FileType.KNOWLEDGE ? StringResources.zhi_shi : StringResources.xue_xi,
                  type == FileType.KNOWLEDGE ? 'knowledge' : 'case',
                  entity.id
                ]).then((value) => context.read<FileListViewModel>().loadData());
                return;
              }
              Navigator.of(context).pushNamed(Routes.master_file_info, arguments: {
                'file': entity,
                'type': type,
                'isMe': isMe,
                'userId': userId,
              }).then((value) => context.read<FileListViewModel>().loadData());
            }
          },
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.w),
                        child: entity.cover != ''
                            ? CachedNetworkImage(
                                imageUrl: ImageUrlUtil.getClean(entity.cover),
                                placeholder: (_, __) => Constants.loadingIcon(),
                                fit: BoxFit.cover,
                              )
                            : Center(
                                child: Image.asset(
                                  'images/default_folder.png',
                                  width: 57.w,
                                  height: 49.w,
                                ),
                              )),
                    decoration: BoxDecoration(
                        color: Color(0xFF0CB7D9),
                        borderRadius: BorderRadius.all(Radius.circular(15.w))),
                  ),
                  ValueListenableProvider.value(
                    value: _privacy,
                    builder: (context, _) {
                      bool select;
                      if (context.watch<bool>()) {
                        select = context.select<FileListViewModel, bool>((value) => entity.myHide);
                      } else {
                        select = context.select<FileListViewModel, bool>((value) => entity.isHide);
                      }
                      if (type == FileType.KNOWLEDGE || type == FileType.APPLY)
                        return Constants.empty;
                      return select
                          ? AbsorbPointer(
                              child: Container(
                                width: double.infinity,
                                height: double.infinity,
                                decoration: BoxDecoration(
                                  color: Colors.white.withAlpha(76),
                                  borderRadius: BorderRadius.circular(15.w),
                                ),
                                child: Center(
                                  child: Image.asset(
                                    'images/icon_privacy.png',
                                    width: 58.w,
                                    height: 58.w,
                                  ),
                                ),
                              ),
                            )
                          : Constants.empty;
                    },
                  ),
                ],
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: 70.h,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.black.withAlpha(30),
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(15.w),
                      bottomRight: Radius.circular(15.w),
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(left: 25.w),
                        width: double.infinity,
                        child: Builder(builder: (context) {
                          String name =
                              context.select<FileListViewModel, String>((value) => entity.name);
                          return Text(
                            name,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: 22.sp,
                                color: Theme.of(context).textTheme.subtitle1.color,
                                fontWeight: FontWeight.w500),
                          );
                        }),
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 25.w),
                        width: double.infinity,
                        child: Builder(builder: (context) {
                          var num = context.select<FileListViewModel, int>((value) => entity.num);
                          return Text(
                            '$num${getName()}',
                            style: TextStyle(fontSize: 18.sp, color: Colors.white),
                          );
                        }),
                      )
                    ],
                  ),
                ),
              ),
              entity.canEdit == 1
                  ? Align(
                      alignment: Alignment.topRight,
                      child: ValueListenableProvider.value(
                        value: _delete,
                        builder: (context, _) {
                          return context.watch<bool>()
                              ? Padding(
                                  padding: EdgeInsets.only(top: 10.w, right: 10.w),
                                  child: Builder(builder: (context) {
                                    bool delete = context.select<FileListViewModel, bool>(
                                        (value) => entity.select == 1);
                                    return delete
                                        ? Image.asset(
                                            'images/selected.png',
                                            width: 28.w,
                                            height: 28.w,
                                          )
                                        : Container(
                                            width: 28.w,
                                            height: 28.w,
                                            decoration: BoxDecoration(
                                                color: Theme.of(context).backgroundColor,
                                                borderRadius: BorderRadius.circular(28.0)),
                                          );
                                  }),
                                )
                              : Constants.empty;
                        },
                      ))
                  : Constants.empty
            ],
          ),
        );
      },
    );
  }

  // 编辑
  void changeName(BuildContext contextMain, FileLoxen file) {
    bool show;
    if (type == FileType.KNOWLEDGE || type == FileType.APPLY) {
      show = false;
    } else {
      show = true;
    }
    showDialog<String>(
      context: contextMain,
      builder: (context) {
        return DialogUtil.getChangeFileNameDialog(context, file, showPrivate: show,
            onChange: (select, name) {
          if (name != null && name.trim() != '') {
            contextMain.read<FileListViewModel>().changeFileName(file, name, select);
          }
        });
      },
    );
  }
}
